﻿using CKS.Core.Framework.Models;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using MiniExcelLibs.Attributes;
using MiniExcelLibs.OpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ZR.Model;
using ZR.Model.Dto.Business.ProductionControl;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.MES.Server.Controllers.Business
{
    [Route("business/CksExport")]
    public class CksExportController : BaseController
    {
        IFreeSql<MesDB> fsql;
        public CksExportController(IFreeSql<MesDB> mesdb)
        {
            fsql = mesdb;
        }


         

        /// <summary>
        /// 按条件查询导出数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("QueryExportData")]
        [Log(Title = "下载子篮模版", BusinessType = BusinessType.EXPORT, IsSaveRequestData = false, IsSaveResponseData = false)]
        [AllowAnonymous]
        public IActionResult QueryExportData([FromQuery]CommonQueryDto parm)
        {
            //
           var op20Datas = fsql.Select<DcCoverrivetingassemble>().AsTable((a, b) => "dc_coverrivetingassemble")
                .WhereIf(parm.BeginTime != null,a=>a.AssembleTime.Between(parm.BeginTime.Value,parm.EndTime.Value))
                .WhereIf(!parm.CoverCode.IsEmpty() ,a=>a.CoverCode.Contains(parm.CoverCode))
                .OrderByDescending(a=>a.Id)
                .Take(parm.Limit).ToList();
            var op30Datas = fsql.Select<DcBottomplaterivetingassemble>().AsTable((a, b) => "dc_bottomplaterivetingassemble")
               .WhereIf(parm.BeginTime != null, a => a.AssembleTime.Value.Between(parm.BeginTime.Value, parm.EndTime.Value))
               .WhereIf(!parm.BottomPlateCode.IsEmpty(), a => a.BottomPlateCode.Contains(parm.BottomPlateCode))
               .OrderByDescending(a => a.Id)
               .Take(parm.Limit).ToList();
            var op50Datas = fsql.Select<DcOp50Record>().AsTable((a, b) => "dc_op50_record")
              .WhereIf(parm.BeginTime != null, a => a.CreatedTime.Value.Between(parm.BeginTime.Value, parm.EndTime.Value))
              .WhereIf(!parm.CoverCode.IsEmpty(), a => a.CoverCode.Contains(parm.CoverCode))
              .OrderByDescending(a => a.Id)
              .Take(parm.Limit).ToList();
            var op60Datas = fsql.Select<DcOp60Record>().AsTable((a, b) => "dc_op60_record")
              .WhereIf(parm.BeginTime != null, a => a.CreatedTime.Value.Between(parm.BeginTime.Value, parm.EndTime.Value))
              .WhereIf(!parm.CoverCode.IsEmpty(), a => a.CoverCode.Contains(parm.CoverCode))
                .WhereIf(!parm.BottomPlateCode.IsEmpty(), a => a.CoverCode.Contains(parm.BottomPlateCode))
              .OrderByDescending(a => a.Id)
              .Take(parm.Limit).ToList();
            var op70Datas = fsql.Select<DcOp70Record>().AsTable((a, b) => "dc_op70_record")
              .WhereIf(parm.BeginTime != null, a => a.CreatedTime.Value.Between(parm.BeginTime.Value, parm.EndTime.Value))
              .WhereIf(!parm.CoverCode.IsEmpty(), a => a.CoverCode.Contains(parm.CoverCode))
                .WhereIf(!parm.BottomPlateCode.IsEmpty(), a => a.CoverCode.Contains(parm.BottomPlateCode))
              .OrderByDescending(a => a.Id)
              .Take(parm.Limit).ToList();
            //将查询结果动态保存到excel

            var sheets = new Dictionary<string, object>
            {
                ["OP20-Record"] = op20Datas,
                ["OP30-Record"] = op30Datas,
                ["OP50-Record"] = op50Datas,
                ["OP60-Record"] = op60Datas,
                ["OP70-Record"] = op70Datas,
            };

            List<DynamicExcelColumn> excelColumns = new List<DynamicExcelColumn>() {
              new DynamicExcelColumn("Id"){Ignore=true},
                    new DynamicExcelColumn("DCId"){ Ignore=true },
                     new DynamicExcelColumn("BigSolderRingBlueCode"){ Ignore=true },
                       new DynamicExcelColumn("SmallSolderRingBlueCode"){ Ignore=true },
                       new DynamicExcelColumn("IsDeleted"){Ignore=true},
                         new DynamicExcelColumn("PalletNo"){Ignore=true},
                          new DynamicExcelColumn("UpdateTime"){Ignore=true},
                          new DynamicExcelColumn("OuterRingFinCount"){Ignore=true},
                          new DynamicExcelColumn("InnerRingFinCount"){Ignore=true},
                          new DynamicExcelColumn("OuterRingFlatness"){Ignore=true},
                           new DynamicExcelColumn("InnerRingFlatness"){Ignore=true},
                    //OuterRingFinCount
                    
                   
            };

            excelColumns= AppendLangColumns(excelColumns);
            

            var config = new OpenXmlConfiguration
            {
                
                DynamicColumns = excelColumns.ToArray()
            };

            var stream = new MemoryStream();
            stream.SaveAs(sheets,configuration:config);
            stream.Seek(0, SeekOrigin.Begin);

            Response.Headers.Append("Access-Control-Expose-Headers", "Content-Disposition");
            return File(stream, 
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                HttpUtility.UrlEncode($"MES-Export-{DateTime.Now.ToString("MMddHHmmss")}.xlsx"));


            // (string, string) result = DownloadImportTemplate("basket");
            //return ExportExcel(result.Item2, result.Item1);
        }

        private List<DynamicExcelColumn> AppendLangColumns(List<DynamicExcelColumn> excelColumns)
        {
            var cols =new DynamicExcelColumn[] {
                //OP20
                new DynamicExcelColumn("AssembleTime") {Name="Time/保存时间", Format = "yyyy-MM-dd HH:mm:ss", Width = 20, Index = 0 },
                new DynamicExcelColumn("CreatedTime") { Name="Time/保存时间",Format = "yyyy-MM-dd HH:mm:ss", Width = 20, Index = 0 },
                new DynamicExcelColumn("CoverCode"){ Name="CoverCode/盖板码" ,Width=15 },
                 new DynamicExcelColumn("CCD_2D1"){ Name="CCD_2D1/圆孔检测结果" },
                  new DynamicExcelColumn("CCD_2D2"){ Name="CCD_2D2/腰孔检测结果" },
                   new DynamicExcelColumn("CCD_3D"){ Name="CCD_3D/3D上盖板检测" },
                 new DynamicExcelColumn("CoverBlueCode"){ Name="CoverBlueCode/盖板子篮" },
                  new DynamicExcelColumn("PressTotalResult"){ Name="PressTotalResult/压装总结果" },
                  new DynamicExcelColumn("PressResult1"){ Name="PressResult1/压装结果1" },
                 new DynamicExcelColumn("PressResult2"){ Name="PressResult2/压装结果2" },
                 new DynamicExcelColumn("PressValue1"){ Name="PressValue1/压力值1" },
                 new DynamicExcelColumn("PressValue2"){ Name="PressValue2/压力值2" },
                  new DynamicExcelColumn("PressDisplacement1"){ Name="PressDisplacement1/压装位移值1" },
                 new DynamicExcelColumn("PressDisplacement2"){ Name="PressDisplacement2/压装位移值2" },

                  
                 new DynamicExcelColumn("HoleDiameter"){ Name="HoleDiameter/圆孔孔径" },
                 new DynamicExcelColumn("SlotWidth"){ Name="SlotWidth/腰孔宽度" },
                 new DynamicExcelColumn("SlotLenUpper"){ Name="SlotLenUpper/槽长度上" },
                 new DynamicExcelColumn("SlotLenLower"){ Name="SlotLenLower/槽长度下" },
                 new DynamicExcelColumn("SlotWidthUpper"){ Name="SlotWidthUpper/槽宽度上" },
                 new DynamicExcelColumn("SlotWidthLower"){ Name="SlotWidthLower/槽宽度下" },
                 new DynamicExcelColumn("Flatness"){ Name="Flatness/平面度" },
                 new DynamicExcelColumn("HeightMax"){ Name="HeightMax/高度最大值" },
                 new DynamicExcelColumn("SmallSolderRingBatchCode"){ Name="SmallSolderRingBatchCode/小焊环批次码" },
                 new DynamicExcelColumn("HeightMin"){ Name="HeightMin/高度最小值" },
                 new DynamicExcelColumn("Profile"){ Name="Profile/轮廓度" },
                 new DynamicExcelColumn("PositionDegree"){ Name="PositionDegree/位置度" },
                 new DynamicExcelColumn("PostRivetingLocatingPinGapL1"){ Name="PostRivetingLocatingPinGapL1/铆后定位柱缝隙（左 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinGapL2"){ Name="PostRivetingLocatingPinGapL2/铆后定位柱缝隙（左 2）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinGapR1"){ Name="PostRivetingLocatingPinGapR1/铆后定位柱缝隙（右 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinGapR2"){ Name="PostRivetingLocatingPinGapR2/铆后定位柱缝隙（右 2）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinHeightL1"){ Name="PostRivetingLocatingPinHeightL1/铆后定位柱高度（左 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinHeightL2"){ Name="PostRivetingLocatingPinHeightL2/铆后定位柱高度（左 2）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinHeightR1"){ Name="PostRivetingLocatingPinHeightR1/铆后定位柱高度（右 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinHeightR2"){ Name="PostRivetingLocatingPinHeightR2/铆后定位柱高度（右 2）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinVerticalityL1"){ Name="PostRivetingLocatingPinVerticalityL1/铆后定位柱垂直度（左 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinVerticalityL2"){ Name="PostRivetingLocatingPinVerticalityL2/铆后定位柱垂直度（左 2）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinVerticalityR1"){ Name="PostRivetingLocatingPinVerticalityR1/铆后定位柱垂直度（右 1）" },
                 new DynamicExcelColumn("PostRivetingLocatingPinVerticalityR2"){ Name="PostRivetingLocatingPinVerticalityR2/铆后定位柱垂直度（右 2）" },
                 new DynamicExcelColumn("LPostRivGapResult"){ Name="LPostRivGapResult/定位柱缝隙(左)" },
                 new DynamicExcelColumn("RPostRivGapResult"){ Name="RPostRivGapResult/定位柱缝隙(右)" },
                 new DynamicExcelColumn("CoverResult"){ Name="CoverResult/盖板检测结果" },
                 new DynamicExcelColumn("TotalResult"){ Name="TotalResult/总结果"  },
                 new DynamicExcelColumn("WRExistence1"){ Name="WRExistence1/焊环有无左(左)" },
                 new DynamicExcelColumn("WRExistence2"){ Name="WRExistence2/焊环有无左(右)" },
                 new DynamicExcelColumn("PPinExistence1"){ Name="PPinExistence1/定位柱有无(左)" },
                 new DynamicExcelColumn("PPinExistence2"){ Name="PPinExistence2/定位柱有无(右)" },

                 //OP30
                 new DynamicExcelColumn("PipeBlueCode"){ Name="PipeBlueCode/管子篮码" },
                 new DynamicExcelColumn("BottomPlateBlueCode"){ Name="BottomPlateBlueCode/底板子篮" },
                 new DynamicExcelColumn("BottomPlateCode"){ Name="BottomPlateCode/底板码" ,Width=15 },
                 new DynamicExcelColumn("RoundHoleDiaInspect"){ Name="RoundHoleDiaInspect/圆孔孔径检测" },
                 new DynamicExcelColumn("SlotHoleWidthInspect"){ Name="SlotHoleWidthInspect/腰孔宽度检测" },
                 new DynamicExcelColumn("LowerODValue1"){ Name="LowerODValue1/下外径值(水嘴1)" },
                 new DynamicExcelColumn("LowerODValue2"){ Name="LowerODValue2/下外径值(水嘴2)" },
                 new DynamicExcelColumn("LowerODResult1"){ Name="LowerODResult1/下外径值(水嘴1)检测结果" },
                 new DynamicExcelColumn("LowerODResult2"){ Name="LowerODResult2/下外径值(水嘴2)检测结果" },
                 new DynamicExcelColumn("RoundnessVal1"){ Name="RoundnessVal1/圆度值1" },
                 new DynamicExcelColumn("RoundnessVal2"){ Name="RoundnessVal2/圆度值2" },
                 new DynamicExcelColumn("RoundnessResult1"){ Name="RoundnessResult1/圆度值1结果" },
                 new DynamicExcelColumn("RoundnessResult2"){ Name="RoundnessResult2/圆度值2结果" },
                 new DynamicExcelColumn("UpperODValue1"){ Name="UpperODValue1/上部外径值1" },
                 new DynamicExcelColumn("UpperODValue2"){ Name="UpperODValue2/上部外径值2" },
                 new DynamicExcelColumn("UpperODResult1"){ Name="UpperODResult1/上部外径值(水嘴1)检测结果" },
                 new DynamicExcelColumn("UpperODResult2"){ Name="UpperODResult2/上部外径值(水嘴2)检测结果" },
                 new DynamicExcelColumn("ConcentricityResult1"){ Name="ConcentricityResult1/同轴度值1结果" },
                 new DynamicExcelColumn("ConcentricityResult2"){ Name="ConcentricityResult2/同轴度值2结果" },
                 new DynamicExcelColumn("ConcentricityVal1"){ Name="ConcentricityVal1/同轴度值1" },
                 new DynamicExcelColumn("ConcentricityVal2"){ Name="ConcentricityVal2/同轴度值2" },
                 new DynamicExcelColumn("ThreeDLineScanResult"){ Name="ThreeDLineScanResult/3d线扫结果" },
                 new DynamicExcelColumn("CircularHoleDetectionResult"){ Name="CircularHoleDetectionResult/圆孔检测结果" },
                 new DynamicExcelColumn("OvalSlotHoleDetectionResult"){ Name="OvalSlotHoleDetectionResult/腰孔检测结果" },
                 new DynamicExcelColumn("PINHeightMax"){ Name="PINHeightMax/PIN 高度最大值" },
                 new DynamicExcelColumn("PINHeightMin"){ Name="PINHeightMin/PIN 高度最小值" },
                 new DynamicExcelColumn("PINFlatness"){ Name="PINFlatness/PIN 平面度" },
                 new DynamicExcelColumn("SlopeProfile"){ Name="SlopeProfile/斜坡面轮廓度" },
                 new DynamicExcelColumn("LeftWallHeight"){ Name="LeftWallHeight/左侧壁高度" },
                 new DynamicExcelColumn("RightWallHeight"){ Name="RightWallHeight/右侧壁高度" },
                 new DynamicExcelColumn("WR1Height"){ Name="WR1Height/焊环1高度" },
                 new DynamicExcelColumn("WR2Height"){ Name="WR2Height/焊环2高度" },
                 new DynamicExcelColumn("WR1Presence"){ Name="WR1Presence/焊环1有无" },
                 new DynamicExcelColumn("WR2Presence"){ Name="WR2Presence/焊环2有无" },
                 new DynamicExcelColumn("OD1Result"){ Name="OD1Result/水嘴1结果" },
                 new DynamicExcelColumn("OD2Result"){ Name="OD2Result/水嘴2结果" },
                 new DynamicExcelColumn("OD1Height"){ Name="OD1Height/水嘴1高度" },
                 new DynamicExcelColumn("OD2Height"){ Name="OD2Height/水嘴2高度" },
                 new DynamicExcelColumn("LocationId"){ Name="LocationId/工位ID" },
                
                 //OP50
                 new DynamicExcelColumn("MiddlePlateBasketCode"){ Name="MiddlePlateBasketCode/中板子篮码" },
                 new DynamicExcelColumn("OD2Result"){ Name="OD2Result/焊片子篮码" },
                 new DynamicExcelColumn("OD1Height"){ Name="OD1Height/圆孔检测 1" },
                 new DynamicExcelColumn("OD2Height"){ Name="OD2Height/圆孔检测 2" },
                 new DynamicExcelColumn("CylinderInspection1"){ Name="CylinderInspection1/圆柱检测 1" },
                 new DynamicExcelColumn("CylinderInspection2"){ Name="CylinderInspection2/圆柱检测 2" },
                 new DynamicExcelColumn("WarpageValue"){ Name="WarpageValue/翘曲值" },
                 new DynamicExcelColumn("Flatness"){ Name="Flatness/平面度" },
                 new DynamicExcelColumn("ProfileXDistance"){ Name="ProfileXDistance/轮廓度 x 距离" },
                 new DynamicExcelColumn("ProfileYDistance"){ Name="ProfileYDistance/轮廓度 y 距离" },
                 new DynamicExcelColumn("PositionDegreeTopLeftCircle"){ Name="PositionDegreeTopLeftCircle/位置度左上圆" },
                 new DynamicExcelColumn("PositionDegreeBottomRightCircle"){ Name="PositionDegreeBottomRightCircle/位置度右下圆" },
                 new DynamicExcelColumn("Thickness"){ Name="Thickness/厚度" },
                 new DynamicExcelColumn("LeftFlatness"){ Name="LeftFlatness/平面度左" },
                 new DynamicExcelColumn("LeftQuantity"){ Name="LeftQuantity/数量左" },
                 new DynamicExcelColumn("MaxSpacingLeftHead"){ Name="MaxSpacingLeftHead/最大间距左头" },
                 new DynamicExcelColumn("MaxSpacingLeftMiddle"){ Name="MaxSpacingLeftMiddle/最大间距左中" },
                 new DynamicExcelColumn("MaxSpacingLeftTail"){ Name="MaxSpacingLeftTail/最大间距左尾" },
                 new DynamicExcelColumn("RightFlatness"){ Name="RightFlatness/平面度右" },
                 new DynamicExcelColumn("RightQuantity"){ Name="RightQuantity/数量右" },
                 new DynamicExcelColumn("MaxSpacingRightHead"){ Name="MaxSpacingRightHead/最大间距右头" },
                 new DynamicExcelColumn("MaxSpacingRightMiddle"){ Name="MaxSpacingRightMiddle/最大间距右中" },
                 new DynamicExcelColumn("MaxSpacingRightTail"){ Name="MaxSpacingRightTail/最大间距右尾" },
                 new DynamicExcelColumn("MidPltInspectRes"){ Name="MidPltInspectRes/中板检测结果" },
                 new DynamicExcelColumn("WeldTabInspectRes"){ Name="WeldTabInspectRes/焊片检测结果" },
                 new DynamicExcelColumn("FinInspectRes"){ Name="FinInspectRes/翅片检测结果" },


                 //OP60
                 new DynamicExcelColumn("WeldingWireBasketCode"){ Name="WeldingWireBasketCode/焊丝子篮码" },
                 new DynamicExcelColumn("WeldingWireSide"){ Name="WeldingWireSide/焊丝正反" },
                 //OP70
                 new DynamicExcelColumn("FixtureId"){ Name="FixtureId/夹具编号" },
                 new DynamicExcelColumn("MaxPressure"){ Name="MaxPressure/最大压力" },
                 new DynamicExcelColumn("MaxDisplacement"){ Name="MaxDisplacement/最大位移" },
                 new DynamicExcelColumn("WeldingWireGap"){ Name="WeldingWireGap/焊丝间隙" },
                 new DynamicExcelColumn("PressingHeight"){ Name="PressingHeight/压装高度" },
                 new DynamicExcelColumn("MisalignmentX"){ Name="MisalignmentX/错位度 X" },
                 new DynamicExcelColumn("MisalignmentY"){ Name="MisalignmentY/错位度 Y" },
                 new DynamicExcelColumn("IndentationDefect"){ Name="IndentationDefect/内陷缺陷" },
                 new DynamicExcelColumn("ToolingGapUpper"){ Name="ToolingGapUpper/工装间隙上" },
                 new DynamicExcelColumn("ToolingGapLower"){ Name="ToolingGapLower/工装间隙下" },
                 //new DynamicExcelColumn("FixtureId"){ Name="FixtureId/" },
           };
            excelColumns.AddRange(cols);

            return excelColumns.GroupBy(m => m.Key)
                               .Select(g => g.First())
                               .ToList();
        }
    }
}
